package mrms.api.web.controllers;

import mrms.api.entity.DeviceEntity;
import mrms.api.entity.UserEntity;
import mrms.api.repository.DeviceRepository;
import mrms.api.web.utils.BeanUtils;
import mrms.api.web.utils.Result;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.xml.ws.Action;

@RestController
@RequestMapping("/device")
public class DeviceController {
    @Autowired
    private DeviceRepository deviceRepository;


    @GetMapping("/select")
    public Result selectDevice(){
        return Result.success(deviceRepository.findAll());
    }

    @PostMapping("/add")
    public Result addDevice(@RequestBody DeviceEntity deviceEntity){
        deviceEntity.setState(0);
        deviceEntity.setUser(null);
        return Result.success(deviceRepository.save(deviceEntity));
    }

    @PostMapping("/update")
    public Result updateDevice(@RequestBody DeviceEntity deviceEntity){
        String id=deviceEntity.getId();
        DeviceEntity deviceEntity1=deviceRepository.findById(id);
        BeanUtils.copyProperties(deviceEntity,deviceEntity1);
        return Result.success(deviceRepository.save(deviceEntity));
    }

    @GetMapping("/lend")
    public Result lendDevice(String deviceId,@RequestAttribute("user") UserEntity user){
        DeviceEntity deviceEntity1=deviceRepository.findById(deviceId);
        deviceEntity1.setState(1);
        deviceEntity1.setUser(user.getId());
        return Result.success(deviceRepository.save(deviceEntity1));
    }

    @GetMapping("/return")
    public Result returnDevice(String deviceId,@RequestAttribute("user") UserEntity user){
        DeviceEntity deviceEntity1=deviceRepository.findById(deviceId);
        deviceEntity1.setState(0);
        deviceEntity1.setUser(null);
        return Result.success(deviceRepository.save(deviceEntity1));
    }



}
